package com.siyoumi.app.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.siyoumi.app.entity.WxUser;
import com.siyoumi.app.mapper.WxUserMapper;
import com.siyoumi.component.XRedis;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.service.ServiceImplBase;
import com.siyoumi.util.XJson;
import org.springframework.stereotype.Service;

//t_wx_user
@Service
public class WxUserService
        extends ServiceImplBase<WxUserMapper, WxUser> {
    static public WxUserService getBean() {
        return XSpringContext.getBean(WxUserService.class);
    }

    public WxUser getEntityMp(String wxappOpenid, String wxappX, String mpX) {
        JoinWrapperPlus<WxUser> query = join();
        query.setAs("wxapp");
        query.join(WxUser.table() + " wx", "wx.wxuser_unionid", "wxapp.wxuser_unionid");
        query.eq("wxapp.wxuser_openid", wxappOpenid)
                .eq("wxapp.wxuser_x_id", wxappX)
                .eq("wx.wxuser_x_id", mpX);
        query.select("wx.*");

        return first(query);
    }

    public WxUser getByOpenid(String openid, String x) {
        QueryWrapper<WxUser> query = q().eq("wxuser_openid", openid)
                .eq("wxuser_x_id", x);
        return first(query);
    }

    public WxUser getByOpenid(String openid) {
        return getByOpenid(openid, true);
    }

    public WxUser getByOpenid(String openid, String x, Boolean getCache) {
        String key = getEntityCacheKey(openid, false);
        String val = XRedis.getBean().getAndSetData(key, k -> {
            return getByOpenid(openid, x);
        }, getCache);

        return XJson.parseObject(val, WxUser.class);
    }

    public WxUser getByOpenid(String openid, Boolean getCache) {
        return getByOpenid(openid, XHttpContext.getX(), getCache);
    }

    public void delCacheByOpenid(String openid) {
        delEntityCache(openid);
    }


    @Override
    public WxUser saveOrUpdatePassEqualField(WxUser entitySrc, WxUser entitySaveOrUpdate) {
        WxUser entity = super.saveOrUpdatePassEqualField(entitySrc, entitySaveOrUpdate);
        Boolean doSet = XHttpContext.get("doSet", false);
        if (doSet) {
            //清缓存
            delCacheByOpenid(entity.getWxuser_openid());
        }

        return entity;
    }
}
